<template>
  <div>
    <div style="margin: 10px 0px">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-input
            style="width: 200px"
            placeholder="宿舍楼栋"
            suffix-icon="el-icon-search"
            v-model="dormitoryBuilding"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
            style="width: 200px"
            placeholder="门牌号"
            suffix-icon="el-icon-search"
            v-model="dormitoryNumber"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
            style="width: 200px"
            placeholder="姓名"
            suffix-icon="el-icon-search"
            v-model="userName"
          ></el-input>
        </el-col>
        <el-col :span="4">
          <el-input
            style="width: 200px"
            placeholder="手机号"
            suffix-icon="el-icon-search"
            v-model="phone"
          ></el-input>
        </el-col>

        <el-button class="ml-5" type="primary" @click="load()">搜索</el-button>
        <el-button type="warning" @click="reset">重置</el-button>
      </el-row>
    </div>

    <div style="margin: 10px 0">
      <el-button type="primary" @click="handleAdd"
        >新增 <i class="el-icon-circle-plus-outline"></i
      ></el-button>
      <el-popconfirm
        class="ml-5"
        confirm-button-text="确定"
        cancel-button-text="我再想想"
        icon="el-icon-info"
        icon-color="red"
        title="您确定批量删除这些数据吗？"
        @confirm="delBatch"
      >
        <el-button type="danger" slot="reference"
          >批量删除 <i class="el-icon-remove-outline"></i
        ></el-button>
      </el-popconfirm>
    </div>

    <el-table
      :data="tableData"
      border
      stripe
      :header-cell-class-name="'headerBg'"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column
        prop="dormitoryBuilding"
        label="宿舍楼栋"
      ></el-table-column>
      <el-table-column prop="dormitoryNumber" label="门牌号"></el-table-column>
      <el-table-column prop="sanitation" label="卫生情况"></el-table-column>
      <el-table-column prop="grade" label="评分" width="180px">
        <template v-slot:default="scope">
          <el-rate v-model="scope.row.grade" show-text> </el-rate>
        </template>
      </el-table-column>
      <el-table-column prop="urlList" label="宿舍图片" width="200">
        <template v-slot:default="scope">
          <div v-for="url in scope.row.urlList" :key="url">
            <div class="demo-image__preview">
              <el-image
                style="width: 100px; height: 100px"
                :src="url"
                :preview-src-list="scope.row.urlList"
              >
              </el-image>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="400" align="center">
        <template slot-scope="scope">
          <el-button type="primary" @click="queryStudent(scope.row)"
            >查看入住的学生</el-button
          >
          <el-button type="success" @click="handleEdit(scope.row)"
            >编辑 <i class="el-icon-edit"></i
          ></el-button>
          <el-popconfirm
            class="ml-5"
            confirm-button-text="确定"
            cancel-button-text="我再想想"
            icon="el-icon-info"
            icon-color="red"
            title="您确定删除吗？"
            @confirm="remove(scope.row)"
          >
            <el-button type="danger" slot="reference"
              >删除 <i class="el-icon-remove-outline"></i
            ></el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding: 10px 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[2, 5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <el-dialog title="宿舍信息" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="90px" size="small">
        <el-form-item label="宿舍楼栋">
          <el-input
            v-model="form.dormitoryBuilding"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="门牌号">
          <el-input
            v-model="form.dormitoryNumber"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="学生信息">
          <el-select v-model="userIdList" multiple placeholder="请选择">
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="卫生情况">
          <el-input v-model="form.sanitation" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="评分">
          <el-rate v-model="form.grade" show-text> </el-rate>
        </el-form-item>
        <el-form-item label="宿舍图片">
          <el-upload
            action="#"
            :http-request="handlerChange"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :before-upload="beforeAvatarUpload"
            :file-list="chooseFileList"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="入住学生列表"
      :visible.sync="queryStudentFlag"
      width="30%"
    >
      <el-table
        :data="userList"
        border
        stripe
        :header-cell-class-name="'headerBg'"
      >
        <el-table-column prop="userName" label="姓名"></el-table-column>
        <el-table-column prop="phone" label="手机号"></el-table-column>
        <el-table-column prop="address" label="家庭住址"></el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Dormitory",
  data() {
    return {
      urlList: [],
      chooseFileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      queryStudentFlag: false,
      form: {},
      tableData: [],
      queryPageReuqest: {},
      dormitoryBuilding: "",
      dormitoryNumber: "",
      userName: "",
      phone: "",
      status: "",
      userIdList: [],
      userList: [],
      multipleSelection: [],
      filesList: [],
      showList: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      dialogFormVisible: false,
      user: localStorage.getItem("user")
        ? JSON.parse(localStorage.getItem("user"))
        : {},
      primaryKey: "",
    };
  },
  created() {
    this.load();
  },
  methods: {
    load() {
      if (this.user.role != "ROLE_ADMIN") {
        this.queryPageReuqest.userId = this.user.id.toString();
      }
      this.queryPageReuqest.pageNo = this.pageNum;
      this.queryPageReuqest.pageSize = this.pageSize;
      this.queryPageReuqest.dormitoryBuilding = this.dormitoryBuilding;
      this.queryPageReuqest.dormitoryNumber = this.dormitoryNumber;
      this.queryPageReuqest.userName = this.userName;
      this.queryPageReuqest.phone = this.phone;
      this.queryPageReuqest.status = this.status;
      console.log(this.queryPageReuqest);
      this.request
        .post("/dormitory/queryPage", this.queryPageReuqest)
        .then((res) => {
          this.tableData = res.records;
          this.total = res.total;
        });
    },
    reset() {
      this.dormitoryBuilding = "";
      this.dormitoryNumber = "";
      this.userName = "";
      this.phone = "";
      this.status = "";
      this.load();
    },
    save() {
      let fileIdList = [];
      this.chooseFileList.forEach((item, index) => {
        fileIdList.push(item.fileId);
      });
      this.form.fileIdList = fileIdList;
      this.form.userIdList = this.userIdList;
      if (this.form.id == null) {
        this.request.post("/dormitory/save", this.form).then((res) => {
          if (res.code === "200") {
            this.$message.success("保存成功");
            this.dialogFormVisible = false;
            this.load();
          } else {
            this.$message.error("保存失败");
          }
        });
      } else {
        this.request.post("/dormitory/update", this.form).then((res) => {
          if (res.code === "200") {
            this.$message.success("更新成功");
            this.dialogFormVisible = false;
            this.load();
          } else {
            this.$message.error("更新失败");
          }
        });
      }
    },
    handleAdd() {
      this.dialogFormVisible = true;
      this.form = {};
      this.userList = [];
      this.userIdList = [];
      this.chooseFileList = [];
      this.request
        .post("/dormitoryUser/getDormitoryUserList", {})
        .then((res) => {
          console.log(res);
          res.forEach((item, index) => {
            this.userList.push(item);
          });
        });
    },
    handleEdit(row) {
      this.userList = [];
      this.userIdList = [];
      this.chooseFileList = [];
      if (row.filesList != null) {
        row.filesList.forEach((item, index) => {
          this.chooseFileList.push(item);
        });
      }
      this.request
        .post("/dormitoryUser/getDormitoryUserList", {
          dormitoryId: row.dormitoryId,
        })
        .then((res) => {
          console.log(res);
          res.forEach((item, index) => {
            this.userList.push(item);
            if (item.status == "USING") {
              this.userIdList.push(item.userId);
            }
          });
        });
      this.form = JSON.parse(JSON.stringify(row));
      this.primaryKey = this.form.id;
      this.dialogFormVisible = true;
    },
    queryStudent(row) {
      this.userList = [];
      this.queryStudentFlag = true;
      this.request
        .post("/dormitoryUser/getDormitoryUserList", {
          dormitoryId: row.dormitoryId,
        })
        .then((res) => {
          console.log(res);
          res.forEach((item, index) => {
            if (item.status == "USING") {
              this.userList.push(item);
            }
          });
        });
    },
    remove(row) {
      this.request
        .post("dormitory/delete", {
          dormitoryId: row.dormitoryId,
        })
        .then((res) => {
          if (res.code === "200") {
            this.$message.success("删除成功");
            this.load();
          } else {
            this.$message.error("删除失败");
          }
        });
    },
    delBatch() {
      let dormitoryIdList = this.multipleSelection.map((v) => v.dormitoryId);
      this.request
        .post("/dormitory/delete/batch", {
          dormitoryIdList: dormitoryIdList,
        })
        .then((res) => {
          if (res.code === "200") {
            this.$message.success("批量删除成功");
            this.load();
          } else {
            this.$message.error("批量删除失败");
          }
        });
    },
    //移除图片
    handleRemove(file, fileInfoList) {
      this.chooseFileList.forEach((item, index) => {
        if (item.name == file.name) {
          this.chooseFileList.splice(index, 1);
        }
      });
    },
    //放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //上传图片
    async handlerChange(param) {
      let formData = new FormData();
      await formData.append("file", param.file);
      this.request.post("/file/saveFile", formData).then((res) => {
        this.chooseFileList.push(res);
      });
    },
    //上传图片前进行校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.load();
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
